use crate::public::Rule;
use sonic_rs::{JsonValueTrait, pointer};
use std::collections::{HashMap, HashSet};
use std::sync::OnceLock;

pub static TICKER_STEP: OnceLock<HashMap<String, f64>> = OnceLock::new();

pub struct Rest;

impl Rule for Rest {
    async fn get_rule(&self) -> HashSet<String> {
        let client = reqwest::Client::new();
        let resp = client
            .get("https://futures.ourbit.com/api/v1/contract/detailV2?client=web")
            .send()
            .await
            .unwrap();

        let body = resp.text().await.unwrap();

        let array = sonic_rs::get_from_str(body.as_str(), &["data"])
            .unwrap()
            .into_array_iter()
            .unwrap();

        let mut set = HashSet::new();
        let mut price_step = HashMap::new();

        for symbol in array {
            let obj = symbol.unwrap();

            if obj.get("state").as_i64().unwrap() != 0
                || obj.get("qc").as_str().unwrap() != "USDT"
                || !obj.get("dne").as_str().unwrap().ends_with("PERPETUAL")
            {
                continue;
            }

            let current_symbol = format!("{}USDT", obj.get("bc").as_str().unwrap());

            let current_price_step: f64 =
                sonic_rs::get_from_str(obj.as_raw_str(), pointer!["dsl", 0])
                    .unwrap()
                    .as_str()
                    .unwrap()
                    .parse()
                    .unwrap();
            price_step.insert(current_symbol.clone(), current_price_step);

            set.insert(current_symbol);
        }

        TICKER_STEP.get_or_init(|| price_step);

        set
    }
}
